package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.WorkDispatchConditionVo;
import com.zb.entity.ZjWorkClientStrategyCondition;
import com.zb.mapper.ZjWorkClientStrategyConditionMapper;
import com.zb.service.ZjWorkClientStrategyConditionService;
import com.zb.vo.WorkClientStrategyConditionChildVo;
import com.zb.vo.WorkClientStrategyConditionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 工单客服分派策略条件表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-27
 */
@Service
public class ZjWorkClientStrategyConditionServiceImpl extends ServiceImpl<ZjWorkClientStrategyConditionMapper, ZjWorkClientStrategyCondition> implements ZjWorkClientStrategyConditionService {
    @Resource
    private ZjWorkClientStrategyConditionMapper workClientStrategyConditionMapper;

    // 新增、修改、删除客服分派条件
    @Override
    public void save(Long custAccId, Long workClientStrategyId, List<WorkClientStrategyConditionVo> conditionVos, List<Long> ids) {
        if (null != ids && !ids.isEmpty()) {
            this.removeByIds(ids);
        }
        Assert.isTrue(null != conditionVos && !conditionVos.isEmpty(), "工单客服分配规则条件不能为空，至少填写一项");
        List<ZjWorkClientStrategyCondition> adds = new ArrayList<>();
        List<ZjWorkClientStrategyCondition> updates = new ArrayList<>();
        ZjWorkClientStrategyCondition condition = null, chilCond;
        for (WorkClientStrategyConditionVo vo : conditionVos) {
            condition = new ZjWorkClientStrategyCondition();
            BeanUtils.copyProperties(vo, condition);
            if (null != condition.getId()) {
                updates.add(condition);
                for (WorkClientStrategyConditionChildVo childVo : vo.getConditionChildVos()) {
                    chilCond = new ZjWorkClientStrategyCondition();
                    BeanUtils.copyProperties(childVo, chilCond);
                    if (null != chilCond.getId()) {
                        updates.add(chilCond);
                        continue;
                    }
                    chilCond.setId(IdWorker.getId());
                    chilCond.setParentId(condition.getId());
                    chilCond.setCustAccId(custAccId);
                    chilCond.setWorkClientStrategyId(workClientStrategyId);
                    adds.add(chilCond);
                }
                continue;
            }
            condition.setId(IdWorker.getId());
            condition.setCustAccId(custAccId);
            condition.setParentId(0L);
            condition.setWorkClientStrategyId(workClientStrategyId);
            condition.setValId(0L);
            condition.setProvince("");
            condition.setCity("");
            condition.setArea("");
            condition.setTown("");
            adds.add(condition);
            for (WorkClientStrategyConditionChildVo childVo : vo.getConditionChildVos()) {
                chilCond = new ZjWorkClientStrategyCondition();
                chilCond.setId(IdWorker.getId());
                chilCond.setParentId(condition.getId());
                chilCond.setCustAccId(custAccId);
                chilCond.setWorkClientStrategyId(workClientStrategyId);
                chilCond.setValId(null == childVo.getValId()? 0L : childVo.getValId());
                chilCond.setProvince(null == childVo.getProvince()? "" : childVo.getProvince());
                chilCond.setCity(null == childVo.getCity()? "" : childVo.getCity());
                chilCond.setArea(null == childVo.getArea()? "" : childVo.getArea());
                chilCond.setTown(null == childVo.getTown()? "" : childVo.getTown());
                adds.add(chilCond);
            }
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }

    // 根据工单客服分派策略表ID获取父级条件名称
    @Override
    public List<ZjWorkClientStrategyCondition> getParentConditionByWorkClientStrategyIds(List<Long> workClientStrategyIds) {
        if (null == workClientStrategyIds || workClientStrategyIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkClientStrategyCondition> wrapper = new QueryWrapper<>();
        wrapper.select("id", "work_client_strategy_id", "type");
        wrapper.in("work_client_strategy_id", workClientStrategyIds).eq("parent_id", 0);
        return this.list(wrapper);
    }

    // 根据工单客服分派策略表ID获取父级条件名称
    @Override
    public List<WorkClientStrategyConditionVo> getParentConditionByWorkClientStrategyId(Long workClientStrategyId) {
        QueryWrapper<ZjWorkClientStrategyCondition> wrapper = new QueryWrapper<>();
        wrapper.select("id", "parent_id", "work_client_strategy_id", "type", "val_id", "province", "city", "area", "town");
        wrapper.eq("work_client_strategy_id", workClientStrategyId);
        List<ZjWorkClientStrategyCondition> conditionList = this.list(wrapper);

        List<WorkClientStrategyConditionVo> voList = conditionList.stream().filter(t -> 0 == t.getParentId()).map(con -> {
            WorkClientStrategyConditionVo vo = new WorkClientStrategyConditionVo();
            BeanUtils.copyProperties(con, vo);
            vo.setConditionChildVos(conditionList.stream().filter(k -> Objects.equals(k.getParentId(), con.getId())).map(j -> {
                WorkClientStrategyConditionChildVo childVo = new WorkClientStrategyConditionChildVo();
                BeanUtils.copyProperties(j, childVo);
                return childVo;
            }).toList());
            return vo;
        }).toList();
        return voList;
    }

    // 根据工单客服分派策略表ID删除
    @Override
    public void deleteBatchByWorkClientStrategyIds(List<Long> workClientStrategyIds) {
        if (null == workClientStrategyIds || workClientStrategyIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjWorkClientStrategyCondition> wrapper = new QueryWrapper<>();
        wrapper.in("work_client_strategy_id", workClientStrategyIds);
        this.remove(wrapper);
    }

    // 根据策略查询是否执行分配
    @Override
    public boolean isExecuteDispatch(WorkDispatchConditionVo workDispatchConditionVo) {
        QueryWrapper<ZjWorkClientStrategyCondition> wrapper = new QueryWrapper<>();
        wrapper.select("id", "type");
        wrapper.eq("work_client_strategy_id", workDispatchConditionVo.getId()).eq("parent_id", 0);
        List<ZjWorkClientStrategyCondition> parentConditions = this.list(wrapper);
        if (CollectionUtils.isEmpty(parentConditions)) {
            return false;
        }
        boolean executeDispatch = true;
        List<Long> parentIds = parentConditions.stream().map(ZjWorkClientStrategyCondition::getId).toList();
        wrapper = new QueryWrapper<>();
        wrapper.select("id", "parent_id", "val_id", "province", "city", "area", "town");
        wrapper.in("parent_id", parentIds);
        List<ZjWorkClientStrategyCondition> childConditions = this.list(wrapper);
        for (ZjWorkClientStrategyCondition pa : parentConditions) {
            // 商品品牌
            if (executeDispatch && pa.getType() == 1) {
                List<Long> brandIds = childConditions.stream().filter(f -> Objects.equals(f.getParentId(), pa.getId())).map(ZjWorkClientStrategyCondition::getValId).distinct().toList();
                executeDispatch = CollectionUtil.containsAny(brandIds, workDispatchConditionVo.getGoodsBrandIds());
            }
            // 商品分类
            if (executeDispatch && pa.getType() == 2) {
                List<Long> typeIds = childConditions.stream().filter(f -> Objects.equals(f.getParentId(), pa.getId())).map(ZjWorkClientStrategyCondition::getValId).distinct().toList();
                executeDispatch = CollectionUtil.containsAny(typeIds, workDispatchConditionVo.getGoodsTypeIds());
            }
            // 客服区域
            if (executeDispatch && pa.getType() == 3) {
                boolean flag = false;
                for (ZjWorkClientStrategyCondition child : childConditions) {
                    if (Objects.equals(child.getParentId(), pa.getId())) {
                        if (Objects.equals(workDispatchConditionVo.getProvince(), child.getProvince())
                                && Objects.equals(workDispatchConditionVo.getCity(), child.getCity())
                                && Objects.equals(workDispatchConditionVo.getArea(), child.getArea())
                                && Objects.equals(workDispatchConditionVo.getTown(), child.getTown())
                        ) {
                            flag = true;
                            break;
                        }
                    }
                }
                executeDispatch = flag;
            }
            // 工单模块
            if (executeDispatch && pa.getType() == 4) {
                executeDispatch = childConditions.stream().anyMatch(f -> Objects.equals(f.getParentId(), pa.getId()) && Objects.equals(workDispatchConditionVo.getModuleId(), f.getValId()));
            }
        }
        return executeDispatch;
    }

}
